package com.joker.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * aop
 *
 * @Author JokerKS
 * @Date 2021/12/05 17:59
 * @Version 1.0
 */
@Aspect
@Component
public class LogAspect {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Pointcut("execution(* com.joker.controller.*.*(..))")
	public void log() {
	}

	@Before("log()")
	public void doBefore(JoinPoint joinPoint) {

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String url = request.getRequestURL().toString();//获取URL
		String ip = request.getRemoteAddr();//获取ip
		String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();//获取方法
		Object[] args = joinPoint.getArgs();//获取参数
		LogServlet logServlet = new LogServlet(url, ip, classMethod, args);

		logger.info("------logServlet:{}--------", logServlet);
	}

	@After("log()")
	public void doAfter() {
		// logger.info("------doAfter--------");
	}

	@AfterReturning(returning = "result", pointcut = "log()")
	public void doAfterReturn(Object result) {
		logger.info("Result:{}", result);

	}

	private class LogServlet {
		private String url;//访问的URL
		private String ip;//访问者的ip
		private String classMethod;//访问的方法
		private Object[] args;//访问参数

		public LogServlet(String url, String ip, String classMethod, Object[] args) {
			this.url = url;
			this.ip = ip;
			this.classMethod = classMethod;
			this.args = args;
		}

		@Override
		public String toString() {
			return "LogServlet{" +
					"url='" + url + '\'' +
					", ip='" + ip + '\'' +
					", classMethod='" + classMethod + '\'' +
					", args=" + Arrays.toString(args) +
					'}';
		}
	}


}
